var express = require('express');
var router = express.Router();

var MongoClient = require('mongodb').MongoClient;

var mongoDB = null;

var mongoURL = "mongodb://127.0.0.1:27017/order";

MongoClient.connect(mongoURL, function (err, db) {
    if (err)console.error("mongodb init error", err);
    mongoDB = db;
    console.log("mongodb init~");
});

/* GET users listing. */
router.get('/', function (req, res) {
    res.send('respond with a resource');
});


router.get('/says', function (req, res) {
    res.render('fuck');
});


router.get('/fuck', function (req, res) {
    mongoDB.collection("fucks").find({},{sort: {'time': -1}}).toArray(function (err, fucks) {
        if (err) {
            res.send([]);
        } else {
            res.send(fucks);
        }
    });
});


router.post('/fuck', function (req, res) {
    var name = req.body.name;
    var uid = req.body.uid;
    var text = req.body.text;
    var obj = {name: name, uid: uid, text: text,time:new Date()};
    console.log(obj);
    mongoDB.collection("fucks").insert(obj, {}, function (err) {
        var result = null;
        if (err) {
            result = {status: "error"};
        } else {
            result = {status: "ok"};
        }
        res.send(result);
    });
});

router.get('/list', function (req, res) {
    mongoDB.collection("user").find().toArray(function (err, users) {
        if (err) {
            res.send([]);
        } else {
            res.send(users);
        }
    });
});


module.exports = router;
